﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Server
{
	class Server
	{
		private AuktionsService auktionsService;
		bool stop;
		int port;

		public Server(AuktionsService auktionsService, int port)
		{
			this.port = port;
			this.auktionsService = auktionsService;
			stop = false;
		}
		/// <summary>
		/// Method used for starting a server
		/// </summary>
		public void Run()
		{
			IPAddress ip = IPAddress.Any;
			TcpListener listener = new TcpListener(ip, port);
			listener.Start();

			while (!stop)
			{
				Socket clientSocket = listener.AcceptSocket();
				if (!stop)
				{
					Clienthandler handler = new Clienthandler(clientSocket, auktionsService);
					auktionsService.ClientInformation("Logon;" + handler.ClientIP);
					auktionsService.BroadCastEvent += handler.SendMessage;
					Thread clientThread = new Thread(handler.Run);
					clientThread.Start();
				}
			}
		}
		/// <summary>
		/// Method used to stop the server and send a message to the clients so they know it's stopping
		/// </summary>
		public void Stop()
		{
			stop = true;
			TcpClient server = new TcpClient("127.0.0.1", 1337);
			auktionsService.Broadcast("ServerClosing");
		}
	}
}
